/*
 *  Document   : main.js
 */
var mainWeb = function() {
    var language = $("#language ul li a"),
        $scrollTop = $('#back-top'),
        $backTop = $(".backtotop"),
        $htmlBody = $('html, body'),
        $spanMenu = $('#menu > span'),
        $divMenu =  $('#menu.m-menu > ul > li.categories > div > .column > div'),
        $moreSpan =  $('span.more'),
        $language = $("#language"),
        $footer = $("#footer h3"),
        $megaMenu =  $('#menu ul > li > a + div');

    // init all action in page
    var initAction = function(){
        $(language).bind("click", function(e){
            if($(this).hasClass("active")) return;
            var language = $(this).data("lang");
            $.ajax({
                url : $(location).attr('pathname'),
                data : {LANG_CODE : language},
                dataType: "html",
                success : function(e){
                    window.location.reload();
                }
            });
        });

        $(window).scroll(function () {
            if ($(this).scrollTop() > 150) {
                $scrollTop.fadeIn();
            } else {
                $scrollTop.fadeOut();
            }
        });

        $backTop.bind("click", function(){
            $htmlBody.animate({scrollTop:0}, 'slow');
        });

        $language.bind("mouseover", function() {
            $(this).find('> ul').slideDown('fast');
            $(this).bind('mouseleave', function() {
                $(this).find('> ul').slideUp('fast');
            });
        });
    }

    /******** Mega Menu **********/
    var initMegaMenu = function(){
        $megaMenu.each(function(index, element) {
            // IE6 & IE7 Fixes
            if ($.browser.msie && ($.browser.version == 7 || $.browser.version == 6)) {
                //var category = $(element).find('a');
                var columns = $(element).find('ul').length;

                $(element).css('width', (columns * 143) + 'px');
                $(element).find('ul').css('float', 'left');
            }

            var menu = $('#menu').offset();
            var dropdown = $(this).parent().offset();

            i = (dropdown.left + $(this).outerWidth()) - (menu.left + $('#menu').outerWidth());

            if (i > 0) {
                $(this).css('margin-left', '-' + (i + 5) + 'px');
            }
        });
    }

    return {
        init: function () {
            initAction();
            initMegaMenu();
        }
    };
}();

/* Initialize WebApp when page loads */
$(function(){ mainWeb.init(); });

